﻿using System.Drawing;

namespace NekoVampire.Extention
{
    public static class ImageExtention
    {
        public static Image GetThumbnailImage(this Image image, int thumbWidth, int thumbHeight)
        {
            return image.GetThumbnailImage(thumbWidth, thumbWidth, delegate { return false; }, System.IntPtr.Zero);
        }

        public static Image GetThumbnailImage(this Image image, int thumbWidth, int thumbHeight, bool fixedAspectRatio)
        {
            int w, h;
            if (!fixedAspectRatio || ((float)image.Width / image.Height) == ((float)thumbWidth / thumbHeight))
            {
                w = thumbWidth;
                h = thumbHeight;
            }
            else
                if ((image.Width / image.Height) < (thumbWidth / thumbHeight))
                {
                    w = (int)(thumbWidth * ((float)image.Width / image.Height));
                    h = thumbHeight;
                }
                else
                {
                    w = thumbWidth;
                    h = (int)(thumbHeight * ((float)image.Height / image.Width));
                }

            return image.GetThumbnailImage(w, h, delegate { return false; }, System.IntPtr.Zero);
        }

        public static Image GetResizedImage(this Image image, int thumbWidth, int thumbHeight)
        {
            return image.GetResizedImage(thumbWidth, thumbHeight, false);
        }

        public static Image GetResizedImage(this Image image, int thumbWidth, int thumbHeight, bool fixedAspectRatio)
        {
            return image.GetResizedImage(thumbWidth, thumbWidth, System.Drawing.Drawing2D.InterpolationMode.Default, fixedAspectRatio);
        }

        public static Image GetResizedImage(this Image image, int thumbWidth, int thumbHeight, System.Drawing.Drawing2D.InterpolationMode interpolationMode, bool fixedAspectRatio)
        {
            int w, h;
            if (!fixedAspectRatio || ((float)image.Width / image.Height) == ((float)thumbWidth / thumbHeight))
            {
                w = thumbWidth;
                h = thumbHeight;
            }
            else
            if ((image.Width / image.Height) < (thumbWidth / thumbHeight))
            {
                w = (int)(thumbWidth * ((float)image.Width / image.Height));
                h = thumbHeight;
            }
            else
            {
                w = thumbWidth;
                h = (int)(thumbHeight * ((float)image.Height / image.Width));
            }

            Bitmap returnImage = new Bitmap(w, h);
            using (Graphics g = Graphics.FromImage(returnImage))
            {
                g.InterpolationMode = interpolationMode;
                g.DrawImage(image, 0, 0, w, h);
            }
            return returnImage;
        }
    }
}